package org.davidliebman.android.awesomewifi;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Date;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

public class LogFileManager {
	boolean mDebug = false;
	public String mContents;
	public File mSdcard;
	public String mName;
	public static final String TAG = new String ("LogFileManager");
	
	public LogFileManager(String mLogfileName, boolean mDebugIn ) {
		this.mName = mLogfileName;
		this.mDebug = mDebugIn;
		mSdcard = Environment.getExternalStorageDirectory();
		mContents = new String("");
		try {
			if (mSdcard.exists() && mDebug) {
				File mFileOutput = new File(mSdcard, mName);
				if (!mFileOutput.exists()){
					mFileOutput.createNewFile();
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void readFile() {
		try {
			int BUFFER_SIZE = 8192;
			File mFileInput = new File(mSdcard, mName);
			FileReader mReader = new FileReader (mFileInput);
			BufferedReader mIn = new BufferedReader(mReader, BUFFER_SIZE);
			ByteArrayOutputStream mBuf = new ByteArrayOutputStream();

			int result = mIn.read();
		    while(result != -1) {
		    	byte b = (byte)result;
		    	mBuf.write(b);
		    	result = mIn.read();
		    }
		    mContents = mBuf.toString();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void insertDate(Context mC) {
		Date mDate = new Date();
		java.text.DateFormat mDateFormat =
		    android.text.format.DateFormat.getDateFormat(mC.getApplicationContext());
		java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(mC);
		String mString = new String ( "Time: " + mDateFormat.format( mDate) + " - " + mTimeFormat.format(mDate));
		this.appendToLog(mString);
	}
	
	public void appendToLog(String mLog) {
		try {
			if (mSdcard.exists() && mDebug) {
				File mFileOutput = new File(mSdcard, mName);
				if (!mFileOutput.exists()){
					mFileOutput.createNewFile();
				}
				FileWriter mWriter = new FileWriter(mFileOutput, true);
				mWriter.append(mLog + "\n");
				mWriter.flush();
				mWriter.close();
			}
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	public String getContents() {
		this.readFile();
		return mContents;
	}
	
}
